package com.fang.udp;

import java.net.*;
import java.util.Scanner;

public class Client extends Thread {
    public Client() {
        super("客户端：");
    }


    @Override
    public void run() {

            try {
                DatagramSocket ds = new DatagramSocket();
                byte[] b = new  byte[1024];
                while (true) {
                    /////////////////////////发送消息//////////////////////////////////
                    String s= Thread.currentThread().getName();
                    Scanner sc = new Scanner(System.in);
                    String strMsg = s+sc.next();
                    DatagramPacket dp = new DatagramPacket(strMsg.getBytes(), strMsg.getBytes().length,
                            new InetSocketAddress("127.0.0.1",8896));

                    ds.send(dp);
                    System.out.println(strMsg);
                    Thread.sleep(1000);



                    //////////////////////////////接收消息///////////////////////////////////////////
                    DatagramPacket dp1 = new DatagramPacket(b,b.length);
                    ds.receive(dp1);
                    int len = dp1.getLength();
                    String str = new String(b,0,len);
                    System.out.println(str);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

